#ifndef _LINUX
#define _LINUX
#endif

#include <pthread.h>
#include "PassiveSocket.h"

#define MAX_PACKET  4096
#define TEST_PACKET "Test Packet"


struct thread_data
{
    char     *pszServerAddr;
    short int nPort;
    int       nNumBytesToReceive;
    int       nTotalPayloadSize;
};


void *CreateTCPEchoServer(void *param)
{
    CPassiveSocket socket;
    CActiveSocket *pClient = NULL;
    struct thread_data *pData = (struct thread_data *)param;
    int            nBytesReceived = 0;
   char result[1024];
    socket.Initialize();
    socket.Listen((const uint8 *)pData->pszServerAddr, pData->nPort);
	printf("enter\n");
    if ((pClient = socket.Accept()) != NULL)
    {
    printf("enter1\n");
	//while (nBytesReceived != pData->nTotalPayloadSize)
	while (1)
	{
	   printf("%d", nBytesReceived);
	    if (nBytesReceived += pClient->Receive(10))
	    {
	   	 //sleep(3000);
	     	memset(result, 0, 1024);
		memcpy(result, pClient->GetData(), 10);
		printf("received: %s\n", result);
		//pClient->Send((const uint8 *)pClient->GetData(), pClient->GetBytesReceived());
	    }
	}

	sleep(100);
	printf("enter2\n");
	delete pClient;
    }
printf("enter3\n");
    socket.Close();

    return NULL;
}

int main(int argc, char **argv)
{
   pthread_t          threadId;
    struct thread_data thData;
    CActiveSocket      client;
    char result[1024];

    thData.pszServerAddr = "192.168.1.163";
    thData.nPort = 6666;
    thData.nNumBytesToReceive = 1;
    thData.nTotalPayloadSize = (int)strlen(TEST_PACKET);


//CreateTCPEchoServer((void *)(&thData));
	
    pthread_create(&threadId, 0, CreateTCPEchoServer, &thData);
	thData.nPort = 7777;
	//pthread_create(&threadId, 0, CreateTCPEchoServer, &thData);
    sleep(2); // allow a second for the thread to create and listen

    client.Initialize();
    //client.SetNonblocking();
   client.SetBlocking();
	printf("enter5\n");
//sleep(5000);
printf("enter4\n");
CPassiveSocket socket;
socket.Initialize();
//socket.Listen(()("192.168.1.163"),8888);
char addr[100] = "192.168.1.163";
char *pchar = addr;
//socket.Listen((uint8 *)pchar, 8888);
//while(1)
//{
//socket.Accept();
//printf("enter7 \n");
//fflush(); 	
//}
printf("enter6 \n");
    if (client.Open((uint8 *)"192.168.1.108", 9999))
    {
	if (client.Send((uint8 *)TEST_PACKET, strlen(TEST_PACKET)))
	{
	    int numBytes = -1;
	    int bytesReceived = 0;

	    client.Select();
		printf("enter8 \n");
	   // while (bytesReceived != strlen(TEST_PACKET))
	   while (1)
	    {
		numBytes = client.Receive(MAX_PACKET);

		if (numBytes > 0)
		{
		    bytesReceived += numBytes;
		    memset(result, 0, 1024);
		    memcpy(result, client.GetData(), numBytes);
		    printf("received: %s\n", result);
			fflush(stdout);
		}
		else
		{
		    printf("Recevied %d bytes\n", numBytes);
			break;
		}
	    }
	}
    }

}
